{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "89e80314",
   "metadata": {},
   "source": [
    "## 获取Access Token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3cfba521",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.422edc0560921bf4b6145f849c49d9cd.315360000.1963882883.282335-25863376', 'expires_in': 2592000, 'session_key': '9mzdCSFbibTwUoz0Ab7gXVAvdZVKq1CMrNAMaiwp/JfWqSVXLIOVNF+XlsSerMrT99M0wsS6iDuF4wbgZTjQLR7hQanKiw==', 'access_token': '24.270f70ae3467a43eddfa7fe780328f17.2592000.1651114883.282335-25863376', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '741401a50396a8b8da46c3bcf10d1508'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "# 网站示例\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=BZNftuKFBvGPVxfrU94xwMG3&client_secret=Z0bP3Ss2sSAFihGjoGxVDBymvH8xp2TR'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e2a35a6c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.f77c2f2da035c08633616bb6c6232ac9.315360000.1963882884.282335-25863376', 'expires_in': 2592000, 'session_key': '9mzdA54lISf1MEdUNK7mW3Lr3vdjVX+idEOnUsvIcdaXozlXwN+35rbSxi+Lv+PWi3rxpkOLbD1bt5+axFdnskzRx2KQ3g==', 'access_token': '24.84970405f0683a174a2a5fefff902ddc.2592000.1651114884.282335-25863376', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '92187f745beac1cd5da05ced317ce155'}\n"
     ]
    }
   ],
   "source": [
    "import requests \n",
    "host = \"https://aip.baidubce.com/oauth/2.0/token\"\n",
    "payload = {\n",
    "    \"grant_type\":\"client_credentials\",\n",
    "    \"client_id\":\"BZNftuKFBvGPVxfrU94xwMG3\",\n",
    "    \"client_secret\":\"Z0bP3Ss2sSAFihGjoGxVDBymvH8xp2TR\"\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b9ab0430",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'refresh_token': '25.f77c2f2da035c08633616bb6c6232ac9.315360000.1963882884.282335-25863376',\n",
       " 'expires_in': 2592000,\n",
       " 'session_key': '9mzdA54lISf1MEdUNK7mW3Lr3vdjVX+idEOnUsvIcdaXozlXwN+35rbSxi+Lv+PWi3rxpkOLbD1bt5+axFdnskzRx2KQ3g==',\n",
       " 'access_token': '24.84970405f0683a174a2a5fefff902ddc.2592000.1651114884.282335-25863376',\n",
       " 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online',\n",
       " 'session_secret': '92187f745beac1cd5da05ced317ce155'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "eb14201f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.84970405f0683a174a2a5fefff902ddc.2592000.1651114884.282335-25863376'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "shena_AT = response.json()[\"access_token\"]\n",
    "shena_AT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b70e8e36",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "20b2ddbc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#  图像识别\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "5df95940",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '郁金香', 'score': 0.605319, 'root': '植物-百合科', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%83%81%E9%87%91%E9%A6%99/13506', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/ca1349540923dd54564eae779c46a4de9c82d158e2d7', 'description': \"郁金香(学名：Tulipa gesneriana L.)是百合科郁金香属的多年生草本植物，具鳞茎。英文名为“Didier's tulip”或“Garden tulip”。叶3-5枚，条状披针形至卵状披针状，花单朵顶生，大型而艳丽，花被片红色或杂有白色和黄色，有时为白色或黄色，长5-7厘米，宽2-4厘米，6枚雄蕊等长，花丝无毛，无花柱，柱头增大呈鸡冠状，花期4-5月。郁金香原产中国古代西域及西藏新疆一带，是土耳其、荷兰、匈牙利等国的国花。\"}}, {'keyword': '郁金香花', 'score': 0.438205, 'root': '植物-花', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%83%81%E9%87%91%E9%A6%99/13506', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/ca1349540923dd54564eae779c46a4de9c82d158e2d7', 'description': \"郁金香(学名：Tulipa gesneriana L.)是百合科郁金香属的多年生草本植物，具鳞茎。英文名为“Didier's tulip”或“Garden tulip”。叶3-5枚，条状披针形至卵状披针状，花单朵顶生，大型而艳丽，花被片红色或杂有白色和黄色，有时为白色或黄色，长5-7厘米，宽2-4厘米，6枚雄蕊等长，花丝无毛，无花柱，柱头增大呈鸡冠状，花期4-5月。郁金香原产中国古代西域及西藏新疆一带，是土耳其、荷兰、匈牙利等国的国花。\"}}, {'keyword': '花卉', 'score': 0.271354, 'root': '商品-农用物资', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%8A%B1%E5%8D%89/229536', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/d6ca7bcb0a46f21fbf3a5f2bf9246b600c33aebf', 'description': '花卉，是具有观赏价值的草本植物，是用来描绘欣赏的植物的统称，喜阳且耐寒，具有繁殖功能的短枝，有许多种类。典型的花，在一个有限生长的短轴上，着生花萼、花瓣和产生生殖细胞的雄蕊与雌蕊。花由花冠、花萼、花托、花蕊组成，有各种各样的颜色，长得也各种各样，有香味或无香味等。'}}, {'keyword': '莲雾', 'score': 0.139263, 'root': '植物-其它', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B4%8B%E8%92%B2%E6%A1%83/704586', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/6d81800a19d8bc3e908ab12d888ba61ea9d34552', 'description': '洋蒲桃(学名：Syzygium samarangense(Bl.)Merr.et Perry)桃金娘科乔木，高12米；嫩枝压扁。叶片薄革质，椭圆形至长圆形，长10-22cm，宽5-8cm，先端钝或稍尖，基部变狭，圆形或微心形，上面干后变黄褐色，下面多细小腺点，侧脉14-19对，以45度开角斜行向上，离边缘5毫米处互相结合成明显边脉，另在靠近边缘1.5毫米处有1条附加边脉，侧脉间相隔6-10毫米，有明显网脉；叶柄极短，长术过4毫米，有时近于无柄。聚伞花序顶生或腋生有花数朵；花白色，花梗长约5毫米；萼管倒圆锥形，长7-8mm，宽6-7mm，萼齿4，半圆形，宽加倍；雄蕊极多；花柱长2.5-3厘米。果实梨形或圆锥形，肉质，洋红色，发亮，长4-5厘米，顶部凹陷，有宿存的肉质萼片；种子1颗。花期3-4月，果实5-6月成熟。原产马来西亚及印度。中国广东、台湾及广西有栽培，供食用。(概述图片来源：)'}}, {'keyword': '草莓', 'score': 0.006462, 'root': '植物-蔷薇科', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%8D%89%E8%8E%93/32702', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/34fae6cd7b899e51993940e442a7d933c9950d8e', 'description': '草莓(英文学名：strawberry、拉丁学名：Fragaria × ananassa Duch.)，多年生草本植物。高10-40厘米，茎低于叶或近相等，密被开展黄色柔毛。叶三出，小叶具短柄，质地较厚，倒卵形或菱形，上面深绿色，几无毛，下面淡白绿色，疏生毛，沿脉较密；叶柄密被开展黄色柔毛。聚伞花序，花序下面具一短柄的小叶；花两性；萼片卵形，比副萼片稍长；花瓣白色，近圆形或倒卵椭圆形。聚合果大，宿存萼片直立，紧贴于果实；瘦果尖卵形，光滑。花期4-5月，果期6-7月。原产南美，中国各地及欧洲等地广为栽培。草莓营养价值高，含有多种营养物质 ，且有保健功效。(概述图片参考： )'}}], 'log_id': 1508650984655770597}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('yujinxiang.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2.酬载准备\n",
    "payload = {\n",
    "    \"access_token\":shena_AT,\n",
    "    \"image\":img,\n",
    "    \"baike_num\":5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "303caba7",
   "metadata": {},
   "source": [
    "## 作业：尝试使用百度API图像识别其中一个，做用户需求分析并设计一个最小可行性应用 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48b120e0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
